package controller;


import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import modal.InventoryItemModal;
import modal.ProductModal;
import modal.UserModal;
import dao.InventoryDAO;
import dao.ProductsDAO;

/**
 * Servlet implementation class HomeController
 */
@WebServlet("/InventController")

public class InventController extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor. 
	 */
	public InventController() {

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doProcess(request, response);
	}
	private void doProcess(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			HttpSession session = request.getSession();
			if (session.getAttribute("user") == null){
				response.sendRedirect("/BidMarket/login.jsp");
			}
			else{
				UserModal user= (UserModal) session.getAttribute("user");
				int userID = user.getUserId();

				InventoryDAO iDao = new InventoryDAO();		
				ArrayList <InventoryItemModal> inventoryProduct=new ArrayList<InventoryItemModal>(iDao.getProductwithUserId(userID));
				iDao.disconnnect();	

				ArrayList<String>inventoryList =new ArrayList<String>();
				for(int i=0; i<inventoryProduct.size(); i++){
					ProductsDAO pDao = new ProductsDAO();	
					int id=inventoryProduct.get(i).getProductId();
					ProductModal p=pDao.getProductwithProductId(id);
					inventoryList.add(""+p.getProductId());
					inventoryList.add(p.getPhotoUrl());
					inventoryList.add(p.getName());
					inventoryList.add(p.getDescription());
					inventoryList.add(p.getPrice());
					pDao.disconnnect();
				}
				session.setAttribute("inventoryList", inventoryList);	
				request.getRequestDispatcher("/inventory.jsp").forward(request, response);	
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
